package com.sdry.web.controller.ljq;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.ljq.Page;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.InventoryOrder;
import com.sdry.model.lz.LossDetail;
import com.sdry.model.lz.LossSpillover;
import com.sdry.model.lz.LzInventoryDetailsCodeEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.ljq.ApprovalManagerService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.LossDetailService;
import com.sdry.service.lz.LossSpilloverService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.utils.ResponseUtil;

@Controller
@RequestMapping("/approvalManager")
public class ApprovalManagerController {

	@Resource
	LossDetailService lossDetailService;
	
	
	@Resource
	LossSpilloverService lossSpilloverService;
	
	@Resource
	ZcInventoryManagementService zcInventoryManagementService;
	
	@Resource
	ApprovalManagerService amService;
	
	@Resource
	CancellingStockDetailService cancellingStockDetailService;
	
	@Resource
	InventoryService inventoryService;
	@Resource
	StockOutOrderService stockOutService;
	@Resource
	ZcBindAndUnbindService zcBindAndUnbindService;
	
	@RequestMapping("/IApprovalPage")
	public void IApprovalPage(Page page,String keyword01,HttpServletResponse response,HttpSession httpSession) {
		
		Map<String,Object> map = new HashMap<>();
		map.put("page", page.getPage());
		map.put("limit",page.getLimit());
		
		ZcSysUserEntity user= (ZcSysUserEntity) httpSession.getAttribute("user");
		
		if(user == null) {
			map.put("approval_id", "1");
		}else {
			map.put("approval_id", user.getId().toString());
		}
		
		
		
		if(null!=keyword01 || ("").equals(keyword01) ) {
			map.put("keyword01", keyword01);
		}else {
			map.put("keyword01", "");
		}
		
		List<LossSpillover> list = amService.IApprovaledQueryPage(map);
		int count = amService.IApprovaledQueryCount(map);
		 JSONObject jsonObject = new JSONObject();
	        JSONArray jsonArray = JSONArray.fromObject(list);
	        jsonObject.put("code", 0);
	        jsonObject.put("data", jsonArray);
	        jsonObject.put("count", count);
	        try {
	            ResponseUtil.write(response, jsonObject);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		
	}
	
	
	@RequestMapping("/ICommitedPage")
	public void ICommitedPage(Page page,String keyword01,HttpServletResponse response,HttpSession httpSession) {
		
		Map<String,Object> map = new HashMap<>();
		map.put("page", page.getPage());
		map.put("limit",page.getLimit());
		
		ZcSysUserEntity user= (ZcSysUserEntity) httpSession.getAttribute("user");
		if(user != null) {
			map.put("creater", user.getId().toString());
		}else{
			map.put("creater", "1");
		}
		if(null!=keyword01 || ("").equals(keyword01) ) {
			map.put("keyword01", keyword01);
		}else {
			map.put("keyword01", "");
		}
		
	
		
		List<LossSpillover> list = amService.ICommitedQueryPage(map);
		int count = amService.ICommitedQueryCount(map);
		 JSONObject jsonObject = new JSONObject();
	        JSONArray jsonArray = JSONArray.fromObject(list);
	        jsonObject.put("code", 0);
	        jsonObject.put("data", jsonArray);
	        jsonObject.put("count", count);
	        try {
	            ResponseUtil.write(response, jsonObject);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		
	}
	
	
	@RequestMapping("/CompleteApproval")
	public void CompleteApproval(long id,String status,String idea,HttpServletResponse response) {
		LossSpillover ls=lossDetailService.queryLossById(id);
	    List<LossDetail> details = lossDetailService.queryMidByLossId(id);
	    if (details!=null&&details.size()>0) { 
			for (LossDetail lossDetail : details) {
				//差异数量为负值
				/*if(lossDetail.getDifference_quantity().intValue()<0) {
					int num=Math.abs(lossDetail.getDifference_quantity().intValue());
				inventoryReduction(lossDetail.getMid(),num);
				}
				else {
					inventoryAdd(lossDetail.getMid(), lossDetail.getDifference_quantity().intValue());
				}*/
				
				//如果差异数量不为0，修改良品库存
				if(lossDetail.getDifference_quantity().intValue() != 0){
					updateInventoryByIdAndNum(lossDetail);
				}
			}
	    }
		Map<String,Object> map = new HashMap<>();
		map.put("id", id);
		map.put("approval_status", status);
		
		if(null != idea || ("").equals(idea)) {
			map.put("approval_idea", idea);
		}else {
			map.put("approval_idea", "");
		}
		
		//Long l=lossSpilloverService.updateLossTabByNum(ls.getInventory_order());
		
		int result = amService.CompleteApproval(map);
		if(result > 0){
			InventoryOrder io = inventoryService.queryInventoryOrderByNumber(ls.getInventory_order());
			if(io != null){
				inventoryService.updateInventoryOrderById(io.getId()+"", "tab", "3");
			}
		}
		
		try {
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**   
	 * 根据损溢单详情修改良品库存
	 * @param lossDetail 损溢单详情实体
	 */
	private void updateInventoryByIdAndNum(LossDetail lossDetail) {
		//1、根据损益单详情的物料ID，找到所有的收货详情ID，然后找到对应的条码）
		List<CodeMark> codeList = lossDetailService.queryCodeById(lossDetail.getMid());
		//2、根据损益单详情，找到盘点单详情ID， 根据盘点单详情找到对应的条码
		List<LzInventoryDetailsCodeEntity> codeList2 = lossDetailService.queryCodeById2(lossDetail.getLoss_spillover_id(), lossDetail.getMid());
		//3、比对条码，如果盘点的条码少，则减库存，盘点的条码多，加库存，相同的条码，比对理论数量和实际数量；
		
		//存有差异的条码的集合
		List<CodeMark> diff = new ArrayList<>();
		//3.1、遍历找到有差异的条码(只是找相同条码的差异数量)
		for(CodeMark cm : codeList){
			for(LzInventoryDetailsCodeEntity idc : codeList2){
				if(cm.getCode().equals(idc.getCode())){
					if(idc.getDiff_num() != 0){
						CodeMark code = new CodeMark();
						code.setCode(idc.getCode());
						code.setNum(idc.getDiff_num());
						diff.add(code);
					}
					cm.setIs_ng(13);
				}
			}
		}
		//3.1.1、 减库存
		for(CodeMark ck : diff){
			//根据条码找到物料ID和批次
			ReceiveDetailQuality receive = inventoryService.queryReceiveByCode(ck.getCode());
			//根据批次和物料ID修改库存数量
			Map<String, Object> map2 = new HashMap<>();
			map2.put("mid", receive.getMid());
			map2.put("mNum", ck.getNum());
			map2.put("pici", receive.getPici());
			map2.put("code", ck.getCode());
			inventoryService.updateInventoryQuantity(map2);
			inventoryService.updateCodeMarkQuantity(map2);
		}
		//3.2、找到库存有，但是盘点没有的条码
		List<CodeMark> chaList = new ArrayList<>();
		for(CodeMark cm2 : codeList){
			if(cm2.getIs_ng() != 13){
				chaList.add(cm2);
			}
		}
		//3.2.1、 删库存条码
		for(CodeMark co : chaList){
			//库存有码，盘点没码，要减库存，所以数量是负的
			co.setNum(0 - co.getNum());
			//根据条码找到物料ID和批次
			ReceiveDetailQuality receive = inventoryService.queryReceiveByCode(co.getCode());
			//根据批次和物料ID修改库存数量
			Map<String, Object> map2 = new HashMap<>();
			map2.put("mid", receive.getMid());
			map2.put("mNum", co.getNum());
			map2.put("pici", receive.getPici());
			inventoryService.updateInventoryQuantity(map2);
			//既然库存没码，那么条码下架，删除多余的码
			ZcMaterielAndTrayEntity infro = zcBindAndUnbindService.selectMaterielLocationByCode(co.getCode());
			if(infro != null){
				zcBindAndUnbindService.downAndUnbind(infro);
			}
			stockOutService.deleteCodemarkOutByCode(co.getCode());
		}
	}


	@RequestMapping("/CompleteApproval1")
	public void CompleteApproval1(long id,String status,String idea,HttpServletResponse response) {
		Map<String,Object> map = new HashMap<>();
		map.put("id", id);
		map.put("approval_status", status);
		
		if(null != idea || ("").equals(idea)) {
			map.put("approval_idea", idea);
		}else {
			map.put("approval_idea", "");
		}
		
		int result = amService.CompleteApproval(map);
		if(result > 0){
			//改盘点单详情状态（改为已盘点）
			//1、根据损益单ID找损益单详情
			List<LossDetail> lossDetails = lossDetailService.queryLossDetail(id);
			//2、根据损溢单ID找损益单
			LossSpillover lossSpillover = lossDetailService.queryLossById(id);
			//3、根据盘点单号找盘点单ID
			Long orderId = inventoryService.queryInventorynum(lossSpillover.getInventory_order());
			for(LossDetail detail : lossDetails){
				//4、根据盘点单ID和物料ID找盘点单详情ID
				Long detailId = inventoryService.queryInventoryDetailByOrderIdAndMid(orderId, detail.getMid());
				inventoryService.updateById(detailId+"", "tab", "0", "lz_inventory_detail");
				//llm 改盘点单状态（改为已盘点）
				inventoryService.updateById(orderId+"", "tab", "1", "lz_inventory_order");
			}
		}
		try {
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 减物料良品库的库存
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryReduction(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		/*for(ZcInventoryInfoEntity info : list){*/
		for(int i = 0; i < list.size(); i++) {
			//System.out.println("补发数量="+materielQuantity+":  库存数量="+info.getmNum());
			materielQuantity = materielQuantity - list.get(i).getSmallNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				//cancellingStockDetailService.deleteInventoryById(info.getId());
				int materielQuantity1;
				materielQuantity1= list.get(i).getBigNum() - materielQuantity ;
				if(materielQuantity1 > 0) {
					//修改库存数量
					Map<String, Object> map = new HashMap<>();
					map.put("id", list.get(i).getId());
					map.put("fieldName", "mNum");
					map.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map);
					Map<String, Object> map1 = new HashMap<>();
					map1.put("id", list.get(i).getId());
					map1.put("fieldName", "bigNum");
					map1.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map1);
					Map<String, Object> map2 = new HashMap<>();
					map2.put("id", list.get(i).getId());
					map2.put("fieldName", "smallNum");
					map2.put("fieldValue", 0);
					cancellingStockDetailService.updateInventory(map2);
					break;
				} else {
					//删除这条数据
					cancellingStockDetailService.deleteInventoryById(list.get(i).getId());
					//求绝对值
					inventoryReduction(list.get(i).getMid(), Math.abs(materielQuantity1));
				}
			} else {
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("fieldName", "smallNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
				Map<String, Object> map1 = new HashMap<>();
				map1.put("id", list.get(i).getId());
				map1.put("fieldName", "mNum");
				map1.put("fieldValue", Math.abs(materielQuantity)+list.get(i).getBigNum());
				cancellingStockDetailService.updateInventory(map1);
			}
			return;
		}
	}
	/**
	 * 增良品库的库存
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryAdd(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//加库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		 if (list!=null&&list.size()>0) { 
			Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(0).getId());
				map.put("fieldName", "smallNum");
				map.put("fieldValue",materielQuantity+list.get(0).getSmallNum());
				cancellingStockDetailService.updateInventory(map);
				Map<String, Object> map1 = new HashMap<>();
				map1.put("id", list.get(0).getId());
				map1.put("fieldName", "mNum");
				map1.put("fieldValue", materielQuantity+list.get(0).getmNum());
				cancellingStockDetailService.updateInventory(map1);
			
		 }
	}
	
	public void inventoryReduction1(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		
		for(int i = 0; i < list.size(); i++) {
			
			materielQuantity = materielQuantity - list.get(i).getmNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				cancellingStockDetailService.deleteInventoryById(list.get(i).getId());
				//求绝对值
				inventoryReduction1(list.get(i).getMid(), Math.abs(materielQuantity));
				
			} else {
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("fieldName", "mNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
			}
			break;
		}
	}
}

